<template>
  <div>
    <el-input :value="roleName" disabled />
    <el-tree
      :data="aclList"
      show-checkbox
      default-expand-all
      node-key="id"
      ref="tree"
      highlight-current
      :default-checked-keys="selectList"
      :props="defaultProps"
      @check="select"
    ></el-tree>
    <el-button type="primary" @click="submitTree">确认</el-button>
    <el-button @click="cancel">取消</el-button>
  </div>
</template>

<script>
import { getUserAclList, setUserAclList } from '@/api/acl/role'

export default {
  name: 'Auth',
  data() {
    return {
      id: '',
      roleName: '',
      aclList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      selectList: [],
      submitList: []
    }
  },
  async mounted() {
    const { id } = this.$route.params
    const { roleName } = this.$route.query
    this.id = id
    this.roleName = roleName
    const res = await getUserAclList(id)
    console.log(res)
    this.aclList = res.children
    this.cycleArray(res.children)
    this.submitList = this.selectList
  },
  methods: {
    //创建方法递归获取选中的id
    cycleArray(array) {
      array.forEach(item => {
        if (item.select && item.id !== '1') {
          this.selectList.push(item.id)
        }
        if (item.children.length) {
          this.cycleArray(item.children)
        }
      })
    },
    //选中
    select(a, b) {
      console.log(b.checkedKeys)
      this.submitList = b.checkedKeys
    },
    //提交
    async submitTree() {
      let { id: userId, submitList } = this
      console.log(submitList)
      const roleId = submitList.join()
      await setUserAclList(userId, roleId)
      this.$message({
        message: '分配成功了呢',
        type: 'success'
      })
      this.$router.history.push({
        name: 'Rloe'
      })
    },

    //取消
    cancel() {
      this.$router.history.push({
        name: 'Rloe'
      })
    }
  }
}
</script>

<style scoped></style>
